<template>
  <div id="goods">
    <div>
      <el-button size="mini" type="primary" icon="el-icon-download" :loading="Loading" @click="downloadImages" v-if="percentage==0||percentage==100">
        批量下载
      </el-button>
      <el-button size="mini" type="primary" icon="el-icon-download" :loading="Loading" @click="downloadImages" v-else>
        正在压缩
        {{percentage}}%
      </el-button>
    </div>
    <listTable 
      @getGoodslist="getGoodslist" 
      :list="list" 
      :loading="loading" 
      :count="count" 
      @receive="getMsg" >
    </listTable>
  </div>
</template>
<script>
// 需要下载
// "file-saver": "^2.0.5",
// "jszip": "^3.10.1",
import FileSaver from 'file-saver'
// 压缩
import JSZip  from 'jszip'
// 上架的商品列表组件
import listTable from "../../components/goods/listTable.vue";
// 获取上架商品列表接口
import { GoodsList} from "./api.js";
export default {
  data() {
    return {
      // 加载标志
      Loading:false,
      flag:true,
      list: [],
      count: 0,
      // 所选择的商品列表
      selectlist:[],
      // 上架商品标志
      loading:false,
      // 下架商品标志
      loading1:false,
      // 下载进度条
      percentage: 0,
    };
  },
  components: {
    listTable,
  },
  mounted() {
    this.getGoodslist(1);
  },
  computed: {
  },
  methods: {
    downloadImages() {
      if (!this.selectlist.length) {
        this.$message.error('未选择商品或选择的商品为下架状态');
        return
      }
      // 加载动画生效
      this.Loading=true
      // 保存每一个文件夹的名字，不能用同一个名字，不然会只下载最后一个
      let vars=[]
      let flag = 0
      let imgNum=0
      let zip = new JSZip();
      let now = new Date();
      let dateTimeString = now.toLocaleString();
      let matchArray = dateTimeString.match(/\d+/g);
      let year = matchArray[0];
      let month = matchArray[1];
      let date = matchArray[2];
      // 将单个数字前面补零
      month = month < 10 ? '0' + month : month;
      date = date < 10 ? '0' + date : date;
      let currentTime = year + month + date
      // 创建currentTime当前时间文件夹，这个文件夹是总的文件夹
      let imgFolder = zip.folder(currentTime);
      for (let index = 0; index < this.selectlist.length; index++) {
        // 将商品内容中有'/'符合的替换成'，',防止创建文件夹出错
        let filecontent = this.selectlist[index].brief.split('/').join(',')
        // 创建子文件夹名称
        vars[index]=imgFolder.folder(filecontent)
        // 图片数组
        let arr = []
        imgNum=imgNum+this.selectlist[index].images.length //计算整个有多少张图片
        // 将图片url存进图片数组
        for (let j = 0; j < this.selectlist[index].images.length; j++) {
          arr.push(this.selectlist[index].images[j].image)
        }
        for (let i = 0; i < arr.length; i++) {      //遍历数组arr
          this.getBase64(arr[i]).then(base64 => {  //调用getBase64()方法,传入图片网络地址得到base64数据
            base64 = base64.split('base64,')[1]
            let x=i+1
            vars[index].file('Goods_img_'+x+ '.png',base64,{ base64: true});//自定义图片名字，存进对应商品文件夹里面
            if (flag === imgNum - 1) {
              // 当图片全部按顺序压缩完后才可以下载
              zip.generateAsync({ type: "blob" }).then((blob) => {
                FileSaver.saveAs(blob, "批量商品图文")//自定义文件压缩包名字
              })
              this.Loading=false
              this.percentage=100
              this.$message({
                message: "压缩成功，浏览器开始下载",
                type: "success",
              });
              return
            }
            flag++
            // 每次压缩成功一张图片，进度条更新
            let number=flag/imgNum
            let number1=parseFloat(number * 100)/ 100
            let number2=number1.toFixed(2)*100
            // 计算进度条
            this.percentage =Math.floor(number2) 
          });
        }
      }
    },
    //传入图片地址，返回base64格式数据
    getBase64(img) {
      var image = new Image();
      image.crossOrigin = 'anonymous';//解决图片跨域问题
      image.src = img;
      return new Promise((resolve, reject) => {
        image.onload = () => {
          resolve(this.getBase64Image(image));
        }
      })
    },
    //创建画布，将图片渲染到画布上，再将画布转为base64格式数据返回出来
    getBase64Image(img, width, height) {
      var canvas = document.createElement("canvas");
      canvas.width = width ? width : img.width;
      canvas.height = height ? height : img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      var dataURL = canvas.toDataURL();
      return dataURL;
    },
    // 接收上架商品子组件的选择的数据
    getMsg(data){
      this.selectlist = data
    },
    // 滚动条置顶
    gundongtioazhiding(){
      // 我这边是.el-main，这个是根据自己来的
      const scrollEle = document.querySelector('.el-main')
      scrollEle.scrollTop=0
    },
    // 获取商品数据
    getGoodslist(page) {
      this.loading=true
      GoodsList({
        page: page,
      }).then(res => {
        this.loading=false
        this.gundongtioazhiding()
        this.list = res.data.results;
        this.count = res.data.count;
      });
    },
  }
};
</script>
<style scoped lang="scss">
.el-input {
  width: 400px;
  margin-right: 12px;
}
.list {
  width: 100%;
  height: 600px;
  background: red;
}
.el-table ::-webkit-scrollbar {
  display: none;
}
.el-pagination {
  visibility: hidden;
}
</style>